package com.gitee.wsl.io.channel.write

import com.gitee.wsl.annotation.InternalAPI
import com.gitee.wsl.io.channel.ByteChannel
import com.gitee.wsl.io.channel.CHANNEL_MAX_SIZE
import com.gitee.wsl.io.channel.read.ext.rethrowCloseCauseIfNeeded
import com.gitee.wsl.io.size
import kotlinx.io.Sink


/**
 * Channel for asynchronous writing of sequences of bytes.
 * This is a **single-writer channel**.
 *
 * Operations on this channel cannot be invoked concurrently, unless explicitly specified otherwise
 * in the description. Exceptions are [close] and [flush].
 */
 interface ByteWriteChannel {

     val isClosedForWrite: Boolean

     val closedCause: Throwable?

    @InternalAPI
     val writeBuffer: Sink

     suspend fun flush()

     suspend fun flushAndClose()

     fun cancel(cause: Throwable?)
}


@InternalAPI
 suspend fun ByteWriteChannel.flushIfNeeded() {
    rethrowCloseCauseIfNeeded()

    if ((this as? ByteChannel)?.autoFlush == true || writeBuffer.size >= CHANNEL_MAX_SIZE) flush()
}
